import re
import sys

from PyQt5.QtCore import QTimer
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox

import qrPrint
import uiDeal
from app_fileDeal import FILE_DEAL
from t5_dt1ui import Ui_MainWindow
from userUart import SerialThread, SerialPortMonitorThread

qrcodePrintFlag = 0  # 二维码标签打印标志 1：已打印 0：未打印


class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.initUI()
        self.error_dialog_shown = False  # 添加标志变量
        self.file_deal = FILE_DEAL()  # 实例化 FILE_DEAL 类
        self.buffer = []  # 用于存储接收到的数据
        self.device_num = None  # 初始化实例变量
        self.update_timer = QTimer(self)  # 创建定时器
        self.update_timer.timeout.connect(self.update_text_edit)  # 连接定时器信号到槽
        self.update_timer.start(100)  # 每 100 毫秒更新一次 UI

    def initUI(self):
        self.mqtt_thread = None
        self.adc_thread = None
        self.uart_thread = None
        self.SerialPort_thread = None
        self.setWindowTitle("捷依工装测试软件")
        self.setWindowIcon(QIcon("logo.ico"))
        # 初始化串口
        SerialThread.update_port_list(self)
        # 按键连接功能
        self.pushButton_2.clicked.connect(self.jyuiInit)  # 清除数据
        self.pushButton_3.clicked.connect(lambda: SerialThread.send_startdata(self))  # 开始测试按键
        self.pushButton_6.clicked.connect(lambda: SerialThread.send_stopdata(self))  # 结束测试按键
        self.pushButton_4.clicked.connect(self.start_serial_thread)  # 打开串口按键
        self.pushButton_5.clicked.connect(SerialThread.send_bluedata)  # 蓝牙打印
        self.pushButton_7.clicked.connect(SerialThread.send_beepdata)  # 蜂鸣器
        self.pushButton_8.clicked.connect(qrPrint.labal_rewind)  # 标签回退
        self.pushButton.clicked.connect(lambda: qrPrint.print_qr_code(self.device_num))
        self.comboBox_5.currentTextChanged.connect(self.setDevTestFun)
        # 设置互斥关系
        self.checkBox_5.toggled.connect(self.toggleBeepCheckBoxes)
        self.checkBox_21.toggled.connect(self.toggleBeepCheckBoxes)
        self.checkBox_6.toggled.connect(self.toggleOledCheckBoxes)
        self.checkBox_22.toggled.connect(self.toggleOledCheckBoxes)
        # 开启可用串口检测线程
        if self.SerialPort_thread is None or not self.SerialPort_thread.isRunning():
            self.SerialPort_thread = SerialPortMonitorThread()
            self.SerialPort_thread.SerialPort.connect(self.handle_SerialPort_signal)
            self.SerialPort_thread.start()

    # 开启串口接收线程
    def start_serial_thread(self):
        print(self.pushButton_4.text())
        if (self.pushButton_4.text() == '打开串口'):
            port = self.comboBox_3.currentText()
            baudrate = int(self.comboBox_4.currentText())
            SerialThread.open_serial(self, port, baudrate)
            if self.uart_thread is None or not self.uart_thread.isRunning():
                return
            self.uart_thread.Serialdata.connect(self.handle_serial_signal)
            return
        if (self.pushButton_4.text() == '关闭串口'):
            self.pushButton_4.setText("打开串口")
            SerialThread.close_serial(self)

    def update_text_edit(self):
        if self.buffer:
            # 一次性更新所有缓冲区中的数据
            self.textEdit_2.append("\n".join(self.buffer))
            self.buffer.clear()  # 清空缓冲区

    # 处理串口接收数据
    def handle_serial_signal(self, message):
        self.buffer.append(message)  # 将接收到的数据添加到缓冲区
        ###################开始测试######################
        if "APP START" in message:
            SerialThread.send_uartFundata(SerialThread, "mkfsTest")
            self.jyuiInit()
        ###################测试数据######################
        if "testflag" in message:
            try:
                # 编译正则表达式
                device_num_pattern = re.compile(r'deviceNum:(\d+)')
                iccid_pattern = re.compile(r'ICCID:(\w+)')
                csq_pattern = re.compile(r'CSQ:(\d+)')
                testflag_pattern = re.compile(r'testflag:(\d+)')
                # 提取数据
                testflag = testflag_pattern.search(message).group(1)
                self.device_num = device_num_pattern.search(message).group(1)
                iccid = iccid_pattern.search(message).group(1)
                csq = csq_pattern.search(message).group(1)
                # 处理测试数据
                result = uiDeal.serDataDeal.testDataToDeal(self, testflag)
                global qrcodePrintFlag  # 声明使用全局变量
                if result == "pass" and qrcodePrintFlag == 0:
                    qrcodePrintFlag = 1
                    qrPrint.print_qr_code(self.device_num)
                    SerialThread.send_uartFundata(SerialThread, "stopTest")
                if result == "error" and qrcodePrintFlag == 1: qrcodePrintFlag = 0
                self.lineEdit.setText(self.device_num)  # 设备号
                self.lineEdit_2.setText(iccid)  # ICCID
                self.lineEdit_3.setText(csq)  # 信号值
                # 写入文件
                port = self.comboBox_3.currentText()
                if self.device_num != "000000000":
                    self.file_deal.file_write(self.device_num, iccid, csq, result, port)
                    self.error_dialog_shown = False  # 成功写入后重置标志
                    self.label.setText(
                        f"本次测试数量: {self.file_deal.write_count}, 文件中总设备数量: {self.file_deal.total_devices}")
                print(self.file_deal.writeErrFlag)
                if self.file_deal.writeErrFlag:  # 文件问题
                    self.error_dialog_shown = True  # 设置标志为 True
                    QMessageBox.information(self, "警告", "数据写入失败", QMessageBox.Yes, QMessageBox.Yes)
                    self.error_dialog_shown = False
            except AttributeError as e:
                print(f"data error!!!!!!!!!: {e}")
            except Exception as e:
                print(f"error!!!!!!!!: {e}")
                if self.file_deal.writeErrFlag:  # 文件问题
                    self.error_dialog_shown = True  # 设置标志为 True
                    QMessageBox.information(self, "警告", "数据写入失败", QMessageBox.Yes, QMessageBox.Yes)
                    self.error_dialog_shown = False


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())
